<?php

namespace app\admin\controller\ykjp\purchase;

use app\common\controller\Backend;
use think\Db;

/**
 * 入库管理
 *
 * @icon fa fa-circle-o
 */
class Storage extends Backend {

    /**
     * Storage模型对象
     * @var \app\admin\model\ykjp\purchase\Storage
     */
    protected $model = null;
    protected $searchFields = "name";
    protected $distinguish = true;
    protected $wherename = "";

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\purchase\Storage;
        $this->view->assign("theWayList", $this->model->getTheWayList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index() {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $this->wherename = "storage.firmid";
            $this->searchFields = "supplier.name";
            // var_dump(11);exit;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            // var_dump($list);exit;
            foreach ($list as $row) {

                $row->getRelation('supplier')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add() {
        $date = date("Y-m-d", time());
        $this->assign("date", $date);
        if ($this->request->isAjax()) {
            $obj = $this->request->param("obj");
            //获取对应供应商的录单
            if ($obj == 3) {
                $supid = $this->request->param("supid");
                $this->model = new \app\admin\model\ykjp\purchase\Order;
                $this->searchFields = "code";
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                        ->where($where)
                        ->where("supplier_id", $supid)
                        ->where("wait_nums", ">", 0)
                        ->where("status", 2)
                        ->order($sort, $order)
                        ->count();
                $list = $this->model
                        ->where("supplier_id", $supid)
                        ->where($where)
                        ->where("status", 2)
                        ->where("wait_nums", ">", 0)
                        ->order($sort, $order)
                        ->select();
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            }
            //获取对应供应商的录单
            if ($obj == 4) {
                $pucId = $this->request->param("ids");
                $order = new \app\admin\model\ykjp\purchase\Order;
                $data = $order->where("firmid", $this->auth->firmid)->where("id", $pucId)->find();
                if ($data) {
                    $partModel = new \app\admin\model\ykjp\information\basisinfo\Partition;
                    $row = $partModel->where("warehouse_id", $data['warehouse_id'])->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
                    $model = new \app\admin\model\ykjp\purchase\Product;
                    $list = $model->with(['products'])->where("wait_nums", ">", 0)->where("purchase_id", $pucId)->where("product.firmid", $this->auth->firmid)->where("product.status", "2")->select();
                    // var_dump($list);exit;
                    $result = array("product" => $list, "code" => $data, "row" => $row);
                    $this->success(null, null, $result);
                }
                $this->error(__('No Results were found'));
            }
            //添加数据
            if ($obj == 5) {
                $row = $this->request->param("row/a");
                $pdct = $this->request->param("product/a");
                $firmid = $this->auth->firmid;
                $admin = $this->auth->id;
                $purchase = "";
                $pdct[0] = isset($pdct[0]) ? $pdct[0] : "";
                if ($pdct[0] == "") {
                    $this->error(__('Please add item'));
                }
                $all = json_decode($pdct[0]);
                $tep = $this->model->object_array($all);
                $supperModel = new \app\admin\model\ykjp\information\basisinfo\Supplier;
                $purchaseModel = new \app\admin\model\ykjp\purchase\Order;
                $purProModel = new \app\admin\model\ykjp\purchase\Product;
                $supper = $supperModel->get(['id' => $row['supplier_id'], "firmid" => $this->auth->firmid]);
                if (!$supper) {
                    $this->error(__('Supplier does not exist'));
                }
                if ($row['purchase_id'] != "") {
                    $purchase = $purchaseModel->get(["id" => $row['purchase_id'], "firmid" => $firmid]);
                    if (!$purchase) {
                        $this->error(__('Purchase does not exist'));
                    }
                }

                $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YKS" . date("ymdHis", time()) . rand(1000, 9999);
                $row['admin_id'] = $admin;
                $row['delivery_time'] = strtotime($row['delivery_time']);
                $row['billing_time'] = strtotime($row['billing_time']);
                $row['createtime'] = time();
                $row['updatetime'] = time();
                $row['firmid'] = $firmid;
                $row['status'] = 0;
                if ($row['purchase_id'] != "") {
                    $row['inbound_type'] = "0";
                }
                $insertId = $this->model->insertGetId($row);

                $arr = [];
                $udapteWait = [];
                $stpModel = new \app\admin\model\ykjp\purchase\Stoproduct;
                $totalNums = 0;
                if ($insertId) {
                    foreach ($tep as $key => $val) {
                        $val['createtime'] = time();
                        $val['storage_id'] = $insertId;
                        $val['updatetime'] = time();
                        $val['status'] = '0';
                        $val['warehouse_id'] = $row['warehouse_id'];
                        $val["firmid"] = $firmid;
                        if ($val['purchase_proid'] != "" && $val['purchase_proid'] > 0) {
                            $getPro = $purProModel->get(['id' => $val['purchase_proid']]);
                            if ($getPro) {
                                $waits = $getPro['wait_nums'] - $val['nums'];
                                $totalNums += $val['nums'];
                                if ($waits < 0) {
                                    $this->model->where("id", $insertId)->delete();
                                    $this->error(__("Inventory shortage"));
                                }
                                $val['wait_nums'] = $getPro['wait_nums'];
                                $udapteWait[] = array("id" => $val["purchase_proid"], "wait_nums" => $waits);
                            }
                        } else {
                            $val['purchase_proid'] = 0;
                        }

                        $arr[] = $val;
                    }
                }

                if ($purchase != "") {
                    $waiNums = $purchase['wait_nums'];
                    $newwait = $waiNums - $totalNums;
                    $purchaseModel->where("id", $row['purchase_id'])->update(array("wait_nums" => $newwait));
                }
                $isnt = $stpModel->insertAll($arr);
                if ($isnt) {
                    if ($udapteWait) {
                        foreach ($udapteWait as $key => $val) {
                            $purProModel->where("id", $val['id'])->update(['wait_nums' => $val['wait_nums']]);
                        }
                    }
                    $this->success(__("insert success"), null, array("result" => "success", "url" => url("/ykjp/purchase/storage/index")));
                } else {
                    $this->model->where("id", $insertId)->delete();
                    $this->error(__("insert fail"));
                }
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null) {
        if ($ids == "") {
            $this->error(__("fail"), "ykjp/purchase/storage/index");
        }
        $this->wherename = "storage.firmid";
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
                ->with(['supplier'])
                ->where($where)
                ->where("storage.id", $ids)
                ->select();
        $purProModel = new \app\admin\model\ykjp\purchase\Product;
        $stpModel = new \app\admin\model\ykjp\purchase\Stoproduct;
        $strProduct = $stpModel->with(['products'])->where("storage_id", $ids)->select();
        foreach ($strProduct as $key => $val) {
            $pro = json_decode($val['products']['prop']);
            $val['products']['prop'] = $this->model->object_array($pro);
            $val['wait_nums'] = 0;
            if ($val['purchase_proid'] != "") {
                $waitNums = $purProModel->where("id", $val['purchase_proid'])->field("wait_nums")->find();
                if ($waitNums) {
                    $val['wait_nums'] = $waitNums['wait_nums'] + $val['nums'];
                }
            }
        }
        $this->assign("detail", $list);
        $this->assign("product", $strProduct);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail() {
        $ids = $this->request->param("ids");
        if ($ids == "") {
            $this->error(__("fail"), "ykjp/purchase/storage/index");
        }
        $this->wherename = "storage.firmid";
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
                ->with(['supplier'])
                ->where($where)
                ->where("storage.id", $ids)
                ->select();
        if (!$list) {
            $this->error(__("Record does not exist"), "ykjp/purchase/storage/index");
        }
        $stpModel = new \app\admin\model\ykjp\purchase\Stoproduct;
        $strProduct = $stpModel->with(['products'])->where("storage_id", $ids)->select();
        foreach ($strProduct as $key => $val) {
            $pro = json_decode($val['products']['prop']);
            $val['products']['prop'] = $this->model->object_array($pro);
        }
        $this->assign("detail", $list);
        $this->assign("product", $strProduct);
        return $this->view->fetch();
    }

    /**
     * 保存
     */
    public function updateData($ids = null) {
        if ($ids == "") {
            $this->error(__("fail"), "ykjp/purchase/storage/index");
        }
        $row = $this->request->param("row/a");
        $product = $this->request->param("product/a");
        if (!$row || $product == "") {
            $this->error(__("fail"));
        }
        $product = json_decode($product[0]);
        $product = $this->model->object_array($product);
        $firmid = $this->auth->firmid;
        $row['updatetime'] = time();
        $row['delivery_time'] = strtotime($row['delivery_time']);
        $row['billing_time'] = strtotime($row['billing_time']);
        $stroIs = $this->model->where("id", $ids)->where("firmid", $firmid)->find();
        if (!$stroIs) {
            $this->error(__("fail"));
        }
        if ($stroIs['status'] != 0) {
            $this->error(__("Current status cannot be edited"));
        }
        if ($stroIs['purchase_id'] != "") {
            $row['inbound_type'] = "0";
        }
        $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YKS" . date("ymdHis", time()) . rand(1000, 9999);

        // 启动事务
        // Db::startTrans();
        // try{
        $this->model->startTrans();
        $result = $this->model->where("id", $ids)->where("firmid", $firmid)->update($row);
        $stpModel = new \app\admin\model\ykjp\purchase\Stoproduct;
        $purProModel = new \app\admin\model\ykjp\purchase\Product;
        $purchaseModel = new \app\admin\model\ykjp\purchase\Order;
        $stpModel->startTrans();
        $purProModel->startTrans();
        $purchaseModel->startTrans();
        if (!$result) {
            $this->error(__("update fail"));
        }
        $where = [];
        foreach ($product as $key => $val) {
            $id = $val['data_id'];
            unset($val['data_id']);
            $purchase_proid = $val['purchase_proid'];
            unset($val['purchase_proid']);
            $val['updatetime'] = time();
            $val['warehouse_id'] = $row['warehouse_id'];
            $val['partition_id'] = $row['partition_id'];
            if ($id) {
                if ($purchase_proid != "" && $purchase_proid > 0) {
                    $stro = $stpModel
                            ->where("id", $id)
                            ->where("firmid", $this->auth->firmid)
                            ->where("storage_id", $ids)
                            ->field("nums")
                            ->find();
                    if (!$stro) {
                        // Db::rollback();
                        $this->model->rollBack();
                        $stpModel->rollBack();
                        $purProModel->rollBack();
                        $purchaseModel->rollBack();
                        $this->error(__("update fail"));
                    }

                    if ($stro['nums'] != $val['nums']) {
                        //获取当前的冻结数
                        $waits = $purProModel
                                ->where("id", $purchase_proid)
                                ->where("firmid", $this->auth->firmid)
                                ->field("wait_nums,nums,purchase_id")
                                ->find();
                        if (!$waits) {
                            // Db::rollback();
                            $this->model->rollBack();
                            $stpModel->rollBack();
                            $purProModel->rollBack();
                            $purchaseModel->rollBack();
                            $this->error(__("update fail"));
                        }
                        $updateNums = $waits['wait_nums'] + $stro['nums'] - $val['nums'];
                        if ($updateNums < 0 || $val['nums'] > $waits['nums']) {
                            $this->model->rollBack();
                            $stpModel->rollBack();
                            $purProModel->rollBack();
                            $purchaseModel->rollBack();
                            $this->error(__("Insufficient %s stock", $key + 1));
                        }
                        $pruche = $purchaseModel->where("id", $waits['purchase_id'])->where("firmid", $this->auth->firmid)->field("wait_nums")->find();
                        if (!$pruche) {
                            // Db::rollback();
                            $this->model->rollBack();
                            $stpModel->rollBack();
                            $purProModel->rollBack();
                            $purchaseModel->rollBack();
                            $this->error(__("update fail"));
                        }
                        $toatwait_nums = $pruche['wait_nums'] - ($val['nums'] - $stro['nums']);
                        $prucheUp = $purchaseModel->where("id", $waits['purchase_id'])->where("firmid", $this->auth->firmid)->update(array("wait_nums" => $toatwait_nums));
                        if (!$prucheUp) {
                            // Db::rollback();
                            $this->model->rollBack();
                            $stpModel->rollBack();
                            $purProModel->rollBack();
                            $purchaseModel->rollBack();
                            $this->error(__("update fail"));
                        }
                    }
                    $updateData = $stpModel->where("id", $id)->where("storage_id", $ids)->update($val);

                    if ($updateData) {
                        $val['nums'] = (int) $val['nums'];
                        if ($stro['nums'] != $val['nums']) {
                            $waitsUpdate = $purProModel
                                    ->where("id", $purchase_proid)
                                    ->where("firmid", $this->auth->firmid)
                                    ->update(array("updatetime" => time(), "wait_nums" => $updateNums));
                            if (!$waitsUpdate) {
                                // Db::rollback();
                                $this->model->rollBack();
                                $stpModel->rollBack();
                                $purProModel->rollBack();
                                $purchaseModel->rollBack();
                                $this->error(__('update fail'));
                            }
                        }
                        $where[] = $id;
                    } else {
                        $this->model->rollBack();
                        $stpModel->rollBack();
                        $purProModel->rollBack();
                        $purchaseModel->rollBack();
                        $this->error(__('update fail'));
                    }
                } else {
                    $updateData = $stpModel->where("id", $id)->where("storage_id", $ids)->update($val);
                    if ($updateData) {
                        $where[] = $id;
                    } else {
                        // Db::rollback();
                        $this->model->rollBack();
                        $stpModel->rollBack();
                        $purProModel->rollBack();
                        $purchaseModel->rollBack();
                        $this->error(__('update fail'));
                    }
                }
            } else {
                $val['storage_id'] = $ids;
                $val['createtime'] = time();
                $val['firmid'] = $firmid;
                $isner = $stpModel->insertGetId($val);
                if ($isner) {
                    $where[] = $isner;
                }
            }
        }
        if ($where) {
            $deletTime = array("deletetime" => time());
            $update = $stpModel->where("storage_id", $ids)->where("id", "not in", $where)->update($deletTime);
        }
        $this->model->commit();
        $stpModel->commit();
        $purProModel->commit();
        $purchaseModel->commit();
        // Db::commit();
        $this->success(__("update success"), null, array("result" => "success"));
    }

    /**
     * 删除
     */
    public function del($ids = null) {
        if ($ids) {
            $firmid = $this->auth->firmid;
            $list = $this->model->where("firmid", $firmid)->where("status", "neq", 3)->where("id", "in", $ids)->select();
            $model = new \app\admin\model\ykjp\purchase\Stoproduct;
            $purchaseModel = new \app\admin\model\ykjp\purchase\Order; //采购单
            $purProModel = new \app\admin\model\ykjp\purchase\Product; //采购产品单
            $this->model->startTrans();
            $model->startTrans();
            $purProModel->startTrans();
            $purchaseModel->startTrans();
            $count = 0;
            foreach ($list as $key => $val) {
                $id = $val['id'];
                $totalNums = 0;
                $purchase_id = $val['purchase_id'];
                $data = array("deletetime" => time());
                $status = $val['status'];
                //删除恢复库存
                $del = $this->model->where("id", $id)->update($data);
                if (!$del) {
                    $this->model->rollback();
                    $model->rollback();
                    $purProModel->rollback();
                    $purchaseModel->rollback();
                    $this->error(__("delete fail"));
                }
                if ($del) {
                    if ($status != 2) {
                        if ($purchase_id != "" & $purchase_id > 0) {
                            $strPorduct = $model->where("storage_id", $id)->select();
                            $prurche = $purchaseModel->where("id", $purchase_id)->find();
                            $totalNums = 0;
                            foreach ($strPorduct as $key => $pro) {
                                $purchase_proid = $pro['purchase_proid'];
                                $pruduct = $purProModel->where("id", $purchase_proid)->find();
                                if ($pruduct) {
                                    $nums = $pruduct['wait_nums'] + $pro['nums'];
                                    $totalNums += $pro['nums'];
                                    $up = $purProModel->where("id", $purchase_proid)->update(array("wait_nums" => $nums));
                                    if (!$up) {
                                        $this->model->rollback();
                                        $model->rollback();
                                        $purProModel->rollback();
                                        $purchaseModel->rollback();
                                        $this->error(__("delete fail"));
                                    }
                                }
                            }
                            if ($totalNums > 0) {
                                $total = $purchaseModel->where("id", $purchase_id)->update(array("wait_nums" => $totalNums));
                                if (!$total) {
                                    $this->model->rollback();
                                    $model->rollback();
                                    $purProModel->rollback();
                                    $purchaseModel->rollback();
                                    $this->error(__("delete fail"));
                                }
                            }
                        }
                        $update = $model->where("storage_id", $val['id'])->select();
                        if (!$update) {
                            $this->model->rollback();
                            $model->rollback();
                            $purProModel->rollback();
                            $purchaseModel->rollback();
                            $this->error(__("delete fail"));
                        }
                    }
                }
                $count += $del;
            }
            if ($count) {
                $this->model->commit();
                $model->commit();
                $purProModel->commit();
                $purchaseModel->commit();
                $this->success();
            } else {
                $this->error();
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 入库
     */
    public function inventory($ids = null) {
        if ($ids) {
            $firmid = $this->auth->firmid;
            $list = $this->model->where("firmid", $firmid)->where("status", "eq", 1)->where("id", "in", $ids)->select();
            $resultCount = 0;
            if ($list) {
                $model = new \app\admin\model\ykjp\purchase\Stoproduct; //入库产品单
                $modelWp = new \app\admin\model\ykjp\inventory\Wp; //库存
                $modelSta = new \app\admin\model\ykjp\inventory\Statement; //库存流水
                $purProModel = new \app\admin\model\ykjp\purchase\Product; //采购产品单
                $purchaseModel = new \app\admin\model\ykjp\purchase\Order; //采购单
                $productModel = new \app\admin\model\ykjp\product\Product; //商品表
                $wareModel = new \app\admin\model\ykjp\information\basisinfo\Warehouse; //仓库
                $partModel = new \app\admin\model\ykjp\information\basisinfo\Partition; //仓库
                //开启事务
                $this->model->startTrans();
                $model->startTrans();
                $modelWp->startTrans();
                $modelSta->startTrans();
                $purProModel->startTrans();
                $purchaseModel->startTrans();
                $productModel->startTrans();
                $wareModel->startTrans();
                $partModel->startTrans();


                foreach ($list as $key => $val) {
                    $id = $val['id'];
                    $count = 0;
                    $purchase_id = $val['purchase_id'];
                    $stoProduct = $model->where("firmid", $firmid)->where("storage_id", $id)->where("status", "1")->select();
                    $totalnums = 0;
                    foreach ($stoProduct as $key => $pro) {
                        $upStrPodu = $model->where("id", $pro['id'])->update(array('status' => 3, "updatetime" => time()));
                        if (!$upStrPodu) {
                            $this->model->rollback();
                            $model->rollback();
                            $modelWp->rollback();
                            $modelSta->rollback();
                            $purProModel->rollback();
                            $purchaseModel->rollback();
                            $productModel->rollback();
                            $wareModel->rollback();
                            $partModel->rollback();
                            $this->error(__('operation failed'));
                        }
                        $count += $upStrPodu;
                        if ($upStrPodu) {
                            $warehouse_id = $pro['warehouse_id'];
                            $partition_id = $pro['partition_id'];
                            $product_id = $pro['product_id'];
                            $where = array(
                                "warehouse_id" => $warehouse_id,
                                "partition_id" => $partition_id,
                                "product_id" => $product_id,
                                "firmid" => $firmid
                            );
                            $isExist = $modelWp->where($where)->find();
                            if ($isExist) {
                                $nums = $isExist['inventory'] + $pro["nums"];
                                $data = array(
                                    "inventory" => $nums,
                                    "updatetime" => time()
                                );
                                //更新已有库存
                                $result = $modelWp->where($where)->update($data);
                            } else {
                                $inserData = array(
                                    "warehouse_id" => $warehouse_id,
                                    "partition_id" => $partition_id,
                                    "product_id" => $product_id,
                                    "firmid" => $firmid,
                                    "inventory" => $pro['nums'],
                                    "updatetime" => time()
                                );
                                //插入新库存
                                $result = $modelWp->insert($inserData);
                            }
                            if (!$result) {
                                $this->model->rollback();
                                $model->rollback();
                                $modelWp->rollback();
                                $modelSta->rollback();
                                $purProModel->rollback();
                                $purchaseModel->rollback();
                                $productModel->rollback();
                                $wareModel->rollback();
                                $partModel->rollback();
                                $this->error(__('operation failed'));
                            }

                            if ($result) {
                                $sle = $productModel->where("id", $pro['product_id'])->where("firmid", $firmid)->find();
                                if ($sle) {
                                    $inNums = $sle['inventory'] + $pro['nums'];
                                    $isUp = $productModel->where("id", $pro['product_id'])->where("firmid", $firmid)->update(array("inventory" => $inNums));
                                    if (!$isUp) {
                                        $this->model->rollback();
                                        $model->rollback();
                                        $modelWp->rollback();
                                        $modelSta->rollback();
                                        $purProModel->rollback();
                                        $purchaseModel->rollback();
                                        $productModel->rollback();
                                        $wareModel->rollback();
                                        $partModel->rollback();
                                        $this->error(__('operation failed'));
                                    }
                                }
                                $sra = $wareModel->where("firmid", $this->auth->firmid)->where("id", $warehouse_id)->find();
                                if ($sra) {
                                    $sra = $sra['inventory'] + $pro['nums'];
                                    $sra = $wareModel->where("firmid", $this->auth->firmid)->where("id", $warehouse_id)->update(array("inventory" => $sra));
                                    if (!$sra) {
                                        $this->model->rollback();
                                        $model->rollback();
                                        $modelWp->rollback();
                                        $modelSta->rollback();
                                        $purProModel->rollback();
                                        $purchaseModel->rollback();
                                        $productModel->rollback();
                                        $wareModel->rollback();
                                        $partModel->rollback();
                                        $this->error(__('operation failed'));
                                    }
                                }
                                $par = $partModel->where("firmid", $this->auth->firmid)->where("id", $partition_id)->find();
                                if ($par) {
                                    $parnums = $par['inventory'] + $pro['nums'];
                                    $par = $partModel->where("firmid", $this->auth->firmid)->where("id", $partition_id)->update(array("inventory" => $parnums));
                                    if (!$par) {
                                        $this->model->rollback();
                                        $model->rollback();
                                        $modelWp->rollback();
                                        $modelSta->rollback();
                                        $purProModel->rollback();
                                        $purchaseModel->rollback();
                                        $productModel->rollback();
                                        $wareModel->rollback();
                                        $partModel->rollback();
                                        $this->error(__('operation failed'));
                                    }
                                }

                                //库存流水
                                $staData = array(
                                    "firmid" => $firmid,
                                    "product_id" => $product_id,
                                    "warehouse_id" => $warehouse_id,
                                    "partition_id" => $partition_id,
                                    "number" => $pro['nums'],
                                    "type" => "采购入库",
                                    "updatetime" => time()
                                );
                                $a = $modelSta->insert($staData);
                                if (!$a) {
                                    $this->model->rollback();
                                    $model->rollback();
                                    $modelWp->rollback();
                                    $modelSta->rollback();
                                    $purProModel->rollback();
                                    $purchaseModel->rollback();
                                    $productModel->rollback();
                                    $wareModel->rollback();
                                    $partModel->rollback();
                                    $this->error(__('operation failed'));
                                }
                                //读取采购单原来对应产品的采购总数
                                if ($pro['purchase_proid'] != "" && $pro['purchase_proid'] > 0) {
                                    $purPorduct = $purProModel->where("firmid", $firmid)->where("id", $pro['purchase_proid'])->find();
                                    if ($purPorduct) {
                                        if ($purPorduct['nums'] == $pro['nums']) {
                                            $totalnums += $pro["nums"];
                                            $upI = $purProModel->where("id", $pro['purchase_proid'])->update(array("status" => "3", "updatetime" => time()));
                                            if (!$upI) {
                                                $this->model->rollback();
                                                $model->rollback();
                                                $modelWp->rollback();
                                                $modelSta->rollback();
                                                $purProModel->rollback();
                                                $purchaseModel->rollback();
                                                $productModel->rollback();
                                                $wareModel->rollback();
                                                $partModel->rollback();
                                                $this->error(__('operation failed'));
                                            }
                                        } else {
                                            $proCount = $model->where("status", "3")->where("purchase_proid", $pro['purchase_proid'])->where("firmid", $firmid)->sum("nums");
                                            $totalnums += $proCount;
                                            if ($proCount == $purPorduct['nums']) {
                                                $updat = $purProModel->where("id", $pro['purchase_proid'])->update(array("status" => "3", "updatetime" => time()));
                                                if ($updat) {
                                                    $this->model->rollback();
                                                    $model->rollback();
                                                    $modelWp->rollback();
                                                    $modelSta->rollback();
                                                    $purProModel->rollback();
                                                    $purchaseModel->rollback();
                                                    $productModel->rollback();
                                                    $wareModel->rollback();
                                                    $partModel->rollback();
                                                    $this->error(__('operation failed'));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // var_dump($count);
                    //修改入库单状态
                    if ($count) {
                        $upStr = $this->model->where("id", $val['id'])->update(array("status" => "3", "updatetime" => time()));
                        if (!$upStr) {
                            $this->model->rollback();
                            $model->rollback();
                            $modelWp->rollback();
                            $modelSta->rollback();
                            $purProModel->rollback();
                            $purchaseModel->rollback();
                            $productModel->rollback();
                            $wareModel->rollback();
                            $partModel->rollback();
                            $this->error(__('operation failed'));
                        }
                        if ($upStr) {
                            $resultCount += $upStr;
                            if ($purchase_id != "" && $purchase_id > 0) {
                                //查找采购单
                                $pusrOrder = $purchaseModel->where("id", $purchase_id)->where("firmid", $firmid)->find();
                                if ($pusrOrder) {
                                    if ($pusrOrder['totalNums'] == $totalnums) {
                                        $pruUp = $purchaseModel->where("id", $purchase_id)->where("firmid", $firmid)->update(array("status" => "3", "storage_status" => "2", "updatetime" => time()));
                                        if (!$pruUp) {
                                            $this->model->rollback();
                                            $model->rollback();
                                            $modelWp->rollback();
                                            $modelSta->rollback();
                                            $purProModel->rollback();
                                            $purchaseModel->rollback();
                                            $productModel->rollback();
                                            $wareModel->rollback();
                                            $partModel->rollback();
                                            $this->error(__('operation failed'));
                                        }
                                    } else {
                                        $uprUp = $purchaseModel->where("id", $purchase_id)->where("firmid", $firmid)->update(array("storage_status" => "1", "updatetime" => time()));
                                        if (!$uprUp) {
                                            $this->model->rollback();
                                            $model->rollback();
                                            $modelWp->rollback();
                                            $modelSta->rollback();
                                            $purProModel->rollback();
                                            $purchaseModel->rollback();
                                            $productModel->rollback();
                                            $wareModel->rollback();
                                            $partModel->rollback();
                                            $this->error(__('operation failed'));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if ($resultCount) {
                $this->model->commit();
                $model->commit();
                $modelWp->commit();
                $modelSta->commit();
                $purProModel->commit();
                $purchaseModel->commit();
                $productModel->commit();
                $wareModel->commit();
                $partModel->commit();
                $this->success(null, null, array("result" => "success"));
            } else {
                $this->model->rollback();
                $model->rollback();
                $modelWp->rollback();
                $modelSta->rollback();
                $purProModel->rollback();
                $purchaseModel->rollback();
                $productModel->rollback();
                $wareModel->rollback();
                $partModel->rollback();
                $this->error(__('operation failed'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 获取仓库信息
     */
    public function getWarehouse() {
        if ($this->request->isAjax()) {
            $type = $this->request->param("type");
            if ($type) {
                $hosemModel = new \app\admin\model\ykjp\information\basisinfo\Warehouse;
                $row = $hosemModel->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
                if ($row) {
                    $this->success('', null, $row);
                }
                $this->error(__('fail'));
            } else {
                $pid = $this->request->param("pid");
                $partModel = new \app\admin\model\ykjp\information\basisinfo\Partition;
                $row = $partModel->where("warehouse_id", $pid)->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
                if ($row) {
                    $this->success('', null, $row);
                }
                $this->error(__('fail'));
            }
        }
        $this->error(__('fail'));
    }

    /**
     * 获取供应商/产品信息
     */
    public function getSupPro($ids = null) {
        if ($this->request->isAjax()) {
            $obj = $this->request->param("obj");
            if ($obj == 1) {
                $this->model = new \app\admin\model\ykjp\information\basisinfo\Supplier;
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                        ->where($where)
                        ->order($sort, $order)
                        ->field("name,contact,phone,description,id")
                        ->count();
                $list = $this->model
                        ->where($where)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->field("name,contact,phone,description,id")
                        ->select();
                $list = collection($list)->toArray();
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            }

            if ($obj == 2) {
                $this->model = new \app\admin\model\ykjp\product\Product;
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();
                $total = $this->model
                        ->where($where)
                        ->order($sort, $order)
                        ->count();
                $list = $this->model
                        ->where($where)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->select();
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            }
            //供应商详情
            if ($obj == 3) {
                $this->model = new \app\admin\model\ykjp\information\basisinfo\Supplier;
                $row = $this->model->get(['id' => $ids, "firmid" => $this->auth->firmid]);
                if (!$row) {
                    $this->error(__('No Results were found'));
                }
                $city = "";
                if ($row) {
                    $row = $row->toArray();
                    if (isset($row['city']) && $row['city'] != "") {
                        $city = explode('/', $row['city']);
                    }
                }
                $this->success(null, null, ['row' => $row, "city" => $city]);
            }

            //获取产品详情

            if ($obj == 4) {
                $this->model = new \app\admin\model\ykjp\product\Product;
                $row = $this->model->get(['id' => $ids, "firmid" => $this->auth->firmid]);
                if (!$row) {
                    $this->error(__('No Results were found'));
                }
                if ($row) {
                    $row = $row->toArray();
                }
                $this->success(null, null, ['row' => $row]);
            }
        }
        $this->error(__('Please use the correct request method'));
    }

    /**
     * 反审批
     */
    public function Anti($ids = "") {
        if ($ids) {
            $isRed = $this->model->where("id", $ids)->where("firmid", $this->auth->firmid)->find();
            if ($isRed) {
                if ($isRed['status'] != 1) {
                    if ($isRed['status'] != 2) {
                        $this->error(__("This order cannot be edited"));
                    }
                    if ($isRed['status'] == 2 && $isRed['purchase_id'] != 0) {
                        $this->error(__("This order cannot be edited"));
                    }
                }
                $model = new \app\admin\model\ykjp\purchase\Stoproduct; //入库产品单
                $update = $this->model->where("id", $ids)->update(array("status" => "0", "updatetime" => time(), "reason" => null));
                if ($update) {
                    $update = $model->where("storage_id", $ids)->update(array("status" => "0", "updatetime" => time()));
                    $this->success(null, null, array("result" => "success"));
                }


                $this->error(__('fail'));
            }
            $this->error(__('fail'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
